<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>

        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import?type=employees')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleExport"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="isSHow = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            sortable=""
            type="index"
            :index="indexMethod"
          />
          <el-table-column label="头像" sortable="">
            <template #default="{ row }">
              <img
                v-imgerror="errImg"
                :src="row.staffPhoto || defaultImg"
                alt=""
                class="staffPhoto"
                @click="handleImgclick(row.staffPhoto )"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatterFn"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="handleRoleAssign(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="del(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination layout="prev, pager, next" />
        </div>
        <!-- 分页-->
        <el-pagination
          :current-page="page"
          :page-sizes="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
          />
        </el-pagination>
      </el-card>

      <!-- 对话框 -->
      <AddEmployee :show-dialog.sync="isSHow" @refresh="getUserList" />

      <!--点击图片 对话框 -->
      <el-dialog title="二维码预览" :visible="showImg" width="30%" @close="showImg=false">
        <!-- 绘制二维码的canvas容器二维码 -->
        <div style="text-align: center">
          <canvas ref="myCancas" class="canvas" />
        </div>
      </el-dialog>
      <!-- 角色权限 -->
      <AssignRole ref="AssignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import Qrcode from 'qrcode'
// Qrcode.toCanvas(放二维码的容器，信息)=>生成二维码
// 放二维码的容器=>必须是canvas标签
import AddEmployee from './components/AddEmployee.vue'
import { reqGetUserList, reqDelEmployee } from '@/api/employees.js'
import obj from '@/constant/employees'
// 处理时间
import dayjs from 'dayjs'
// 错误图片
import errImg from '@/assets/common/bigUserHeader.png'
// 分配角色权限
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  data() {
    return {
      list: [], // 列表
      page: 1, // 当前页
      size: 5, // 每页条数
      total: 0, // 总数,
      loading: false,
      isSHow: false, // 对话框
      defaultImg:
        'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      errImg: errImg, // 错误图片
      showImg: false, // 图片二维码对话框
      showRoleDialog: false, // 角色权限对话框的显示
      userId: ''// 角色权限的ID
    }
  },
  created() {
    // 获取员工列表
    this.getUserList()
  },
  methods: {
    async getUserList() {
      this.loading = true
      // 获取员工列表
      const {
        data: { rows, total }
      } = await reqGetUserList(this.page, this.size)
      // 列表
      this.list = rows
      // 和
      this.total = total
      // loading
      this.loading = false
    },
    // 每页条数
    handleSizeChange(val) {
      // 改变每页条数
      this.size = val
      // 回到第一页
      this.page = 1
      // 重新发请求
      this.getUserList()
    },
    // 当前页
    handleCurrentChange(val) {
      // 当前页
      this.page = val
      // 重新发请求
      this.getUserList()
    },
    // 自定义下标
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    // 列的内容如果需要格式化formatter，函数的返回值
    formatterFn(row, column, cellValue, index) {
      // return cellValue === 1 ? '正式员工' : '临时工'
      const { hireType } = obj
      const res = hireType.find((item) => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    // 删除角色
    del(id) {
      this.$confirm('确定要删除吗，不可逆转', '温馨提示')
        .then(async() => {
          const res = await reqDelEmployee(id)
          this.$message.success(res.message)
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          // 获取员工列表
          this.getUserList()
        })
        .catch(() => {
          this.$message.info('您已经取消')
        })
    },
    // 转换成二维数组
    tranListTo2d(rows, header, headersRelations) {
      const res = []

      rows.forEach((item) => {
        const arr = []

        header.forEach((key) => {
          const englishKey = headersRelations[key]

          let val = item[englishKey]
          // 处理日期
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          // 聘用形式
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resObj = hireType.find((v) => v.id === +val)
            val = resObj ? resObj.value : '未知'
          }
          arr.push(val)
        })

        res.push(arr)
      })
      return res
    },
    // 导出Excel
    async handleExport() {
      const header = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]

      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      // 获取员工列表
      const {
        data: { rows }
      } = await reqGetUserList(1, Infinity)
      // 转换成二维数组
      const res = this.tranListTo2d(rows, header, headersRelations)
      console.log(res)
      // import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header,
      //     data: res,
      //     filename: '我的表格',
      //     autoWidth: true,
      //     bookType: 'xlsx'
      //   })
      // })
    },
    // 点击头像 显示对话框
    handleImgclick(imgUrl) {
      if (!imgUrl) {
        return
      }
      // 控制对话框显示
      this.showImg = true
      // vue异步更新视图，等会才会渲染canva容器
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.myCancas, imgUrl)
      })
    },
    // 角色添加权限
    handleRoleAssign(id) {
      // 显示弹窗
      this.showRoleDialog = true
      // 赋值id
      this.userId = id
      // 发请求获员工列表
      // this.$refs.AssignRole.getRoleLise()
      // 发请求获取员工详情
      // this.$refs.AssignRole.getRoleDeatil()
    }
  }
}
</script>

<style lang='scss' scoped>
.staffPhoto {
  width: 70px;
  height: 70px;
  // border-radius: 50%;
}
</style>
